package bb.lanxing.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Parcelable;

import com.baidu.platform.comapi.map.MapBundleKey;
import com.umeng.analytics.pro.d;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import bb.lanxing.App;
import bb.lanxing.manager.TWatchManager;
import bb.lanxing.model.database.LaunchBanner;
import bb.lanxing.model.database.Workout;
import bb.lanxing.mvp.model.LaunchBannerModelImpl;
import bb.lanxing.mvp.presetner.PoiImagePresenter;
import bb.lanxing.mvp.presetner.WorkoutSyncPresenterImpl;
import bb.lanxing.mvp.presetner.i.IWorkoutSyncPresenter;
import bb.lanxing.util.Enums;
import bb.lanxing.util.Log;
import bb.lanxing.util.RxPermissionUtil;

public class SyncTaskService extends Service {
    public static final String ACTION_SYNC_ALREADY_SYNC = "bb.lanxing.ACTION.sync.running";
    public static final String ACTION_SYNC_ITEM_PROGRESS = "bb.lanxing.ACTION.sync.item.progress";
    public static final String ACTION_SYNC_ITEM_RESULT = "bb.lanxing.ACTION.sync.item.result";
    public static final String ACTION_SYNC_WORKOUTS_FINISH = "bb.lanxing.ACTION.sync.workout.stop";
    public static final String ACTION_SYNC_WORKOUTS_START = "bb.lanxing.ACTION.sync.workout.start";
    public static final String EXTRA_ONLY_WIFI = "sync_only_wifi";
    public static final String EXTRA_SUCCESS = "success";
    public static final String EXTRA_TASK_ID = "sync_task_id";
    public static final String EXTRA_WORKOUT = "extra_workout";
    public static final String EXTRA_WORKOUTS = "extra_workouts";
    public static final String EXTRA_WORKOUT_ID = "workoutId";
    private static final String TAG = "SyncTaskService";
    public static final int TASK_SYNC_LAUNCH_IMAGE = 4;
    public static final int TASK_SYNC_POI_PHOTO = 2;
    public static final int TASK_SYNC_WORKOUT = 1;
    private Handler handler;
    private int runningTask;
    private LinkedList<SyncTask> syncTasks;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    static int whenDestroy(SyncTaskService syncTaskService, int i) {
        int i2 = i & syncTaskService.runningTask;
        syncTaskService.runningTask = i2;
        return i2;
    }

    static int whenTask(SyncTaskService syncTaskService, int i) {
        int i2 = i | syncTaskService.runningTask;
        syncTaskService.runningTask = i2;
        return i2;
    }

    public SyncTaskService() {
        super();
        this.runningTask = 0;
        this.handler = new Handler(Looper.getMainLooper());
    }

    public static void startSyncService(Context context, int id, boolean onlyWifi) {
        Intent intent = new Intent(context, SyncTaskService.class);
        intent.putExtra(EXTRA_TASK_ID, id);
        intent.putExtra(EXTRA_ONLY_WIFI, onlyWifi);
        context.startService(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        if (intent == null) {
            return Service.START_STICKY;
        }

        int intExtra = intent.getIntExtra(EXTRA_TASK_ID, 0);
        if (intExtra == TASK_SYNC_WORKOUT) {//1
            syncWorkout(intent);
        } else if (intExtra == TASK_SYNC_POI_PHOTO) {//2
            syncPoiImage(intent);
        } else if (intExtra == TASK_SYNC_LAUNCH_IMAGE) {//4
            checkLaunchImage(intent);
        }

        return Service.START_STICKY;
    }

    private void syncPoiImage(Intent intent) {
        if (App.networkState == Enums.NetworkState.disable) {
            return;
        }
        PoiImagePresenter poiImagePresenter = new PoiImagePresenter();
        long longExtra = intent.getLongExtra("image_id", -1L);
        if (longExtra != -1) {
            poiImagePresenter.uploadImage(longExtra);
        } else {
            poiImagePresenter.syncWithServer();
        }
    }

    public boolean checkStoragePermission() {
        return RxPermissionUtil.getInstance().checkPermission(this, RxPermissionUtil.getStoragePermissions());
    }

    private void syncWorkout(Intent intent) {
        addTask(1, intent.getBooleanExtra(EXTRA_ONLY_WIFI, false), new WorkoutSyncTask(intent));
    }


    public class WorkoutSyncTask extends SyncTask<Workout> {
        Runnable cancel;
        final Intent intent;
        IWorkoutSyncPresenter workoutSyncPresenter;


        WorkoutSyncTask(Intent intent) {
            super();
            this.intent = intent;
            this.cancel = () -> WorkoutSyncTask.this.workoutSyncPresenter.release();
        }

        @Override
        public void onProgress(Workout workout, Map<String, Object> map) {
            onProgress2(workout, map);
        }

        @Override
        public void onUpdate(Workout workout, Map<String, Object> map) {
            onUpdate2(workout, map);
        }

        @Override
        void run() {
            long longExtra = this.intent.getLongExtra("workout_id", -1L);
            WorkoutSyncPresenterImpl workoutSyncPresenterImpl = new WorkoutSyncPresenterImpl(this);
            this.workoutSyncPresenter = workoutSyncPresenterImpl;
            if (longExtra > 0) {
                workoutSyncPresenterImpl.syncWorkout(longExtra);
            } else if (App.getContext().isUserSignin()) {
                this.workoutSyncPresenter.syncWorkoutAll(App.getContext().getUserId());
            }
            SyncTaskService.this.handler.postDelayed(this.cancel, 30000L);//c.k
        }

        @Override
        public void onStart(List<Workout> list) {
            if (list.isEmpty()) {
                destroy();
            }
            Intent buildBroadcastIntent = buildBroadcastIntent(SyncTaskService.ACTION_SYNC_WORKOUTS_START);
            buildBroadcastIntent.putExtra(SyncTaskService.EXTRA_WORKOUTS, new ArrayList<>(list));
            buildBroadcastIntent.putExtra(TWatchManager.WORKOUT_START, true);
            buildBroadcastIntent.putExtra("size", list.size());
            SyncTaskService.this.sendBroadcast(buildBroadcastIntent);
        }


        public void onUpdate2(Workout workout, Map<String, Object> map) {
            if (workout != null) {
                Intent buildBroadcastIntent = buildBroadcastIntent(SyncTaskService.ACTION_SYNC_ITEM_RESULT);
                buildBroadcastIntent.putExtra(SyncTaskService.EXTRA_WORKOUT, (Parcelable) workout);
                if (map.containsKey(SyncTaskService.EXTRA_WORKOUT_ID)) {
                    buildBroadcastIntent.putExtra(SyncTaskService.EXTRA_WORKOUT_ID, (Long) map.get(SyncTaskService.EXTRA_WORKOUT_ID));
                }
                if (map.containsKey("progress")) {
                    buildBroadcastIntent.putExtra("progress", (Double) map.get("progress"));
                }
                if (map.containsKey("success")) {
                    buildBroadcastIntent.putExtra("success", (Boolean) map.get("success"));
                }
                if (map.containsKey(d.O)) {
                    buildBroadcastIntent.putExtra(d.O, (String) map.get(d.O));
                }
                buildBroadcastIntent.putExtra(MapBundleKey.MapObjKey.OBJ_SL_INDEX, (Integer) map.get(MapBundleKey.MapObjKey.OBJ_SL_INDEX));
                SyncTaskService.this.sendBroadcast(buildBroadcastIntent);
                Log.d(SyncTaskService.TAG, "onUpdate --- success = " + map.get("success") + " index = " + map.get(MapBundleKey.MapObjKey.OBJ_SL_INDEX));
            }
        }


        public void onProgress2(Workout workout, Map<String, Object> map) {
            if (workout != null) {
                Intent buildBroadcastIntent = buildBroadcastIntent(SyncTaskService.ACTION_SYNC_ITEM_PROGRESS);
                buildBroadcastIntent.putExtra(SyncTaskService.EXTRA_WORKOUT, (Parcelable) workout);
                if (map.containsKey(SyncTaskService.EXTRA_WORKOUT_ID)) {
                    buildBroadcastIntent.putExtra(SyncTaskService.EXTRA_WORKOUT_ID, (Long) map.get(SyncTaskService.EXTRA_WORKOUT_ID));
                }
                if (map.containsKey("progress")) {
                    buildBroadcastIntent.putExtra("progress", (Double) map.get("progress"));
                }
                SyncTaskService.this.sendBroadcast(buildBroadcastIntent);
                Log.d(SyncTaskService.TAG, "onProgress --- progress = " + map.get("progress"));
            }
        }

        @Override
        public void onFinish(List<Workout> list, List<Workout> list2) {
            Intent buildBroadcastIntent = buildBroadcastIntent(SyncTaskService.ACTION_SYNC_WORKOUTS_FINISH);
            ArrayList<Workout> arrayList = new ArrayList<>(list);
            arrayList.addAll(list2);
            buildBroadcastIntent.putExtra(SyncTaskService.EXTRA_WORKOUTS, arrayList);
            buildBroadcastIntent.putExtra(TWatchManager.WORKOUT_START, false);
            buildBroadcastIntent.putExtra("success_size", list.size());
            buildBroadcastIntent.putExtra("fail_size", list2.size());
            SyncTaskService.this.sendBroadcast(buildBroadcastIntent);
            SyncTaskService.this.handler.removeCallbacks(this.cancel);
            super.onFinish(list, list2);
        }
    }

    private void checkLaunchImage(Intent intent) {
        addTask(TASK_SYNC_LAUNCH_IMAGE, intent.getBooleanExtra(EXTRA_ONLY_WIFI, false), new SyncTask<LaunchBanner>() {
            public void onProgress2(LaunchBanner launchBanner, Map<String, Object> map) {
            }

            @Override
            public void onStart(List<LaunchBanner> list) {
            }

            public void onUpdate2(LaunchBanner launchBanner, Map<String, Object> map) {
            }

            @Override
            public void onProgress(LaunchBanner launchBanner, Map map) {
                onProgress2(launchBanner, (Map<String, Object>) map);
            }

            @Override
            public void onUpdate(LaunchBanner launchBanner, Map map) {
                onUpdate2(launchBanner, (Map<String, Object>) map);
            }

            @Override
            void run() {
                LaunchBannerModelImpl launchBannerModelImpl = new LaunchBannerModelImpl();
                if (SyncTaskService.this.checkStoragePermission()) {
                    for (LaunchBanner launchBanner : launchBannerModelImpl.getValidBanner()) {
                        launchBannerModelImpl.downloadBannerImage(launchBanner);
                    }
                }
                destroy();
            }
        });
    }


    public abstract class SyncTask<T extends Parcelable> implements Serializable {
        private int taskId;
        private boolean wifiSync;

        public abstract void onProgress(T t, Map<String, Object> map);

        public abstract void onStart(List<T> list);

        public abstract void onUpdate(T t, Map<String, Object> map);

        abstract void run();

        public SyncTask() {
        }

        void setTaskId(int i) {
            this.taskId = i;
            SyncTaskService.whenTask(SyncTaskService.this, i);
        }

        void setWifiSync(boolean z) {
            this.wifiSync = z;
        }

        boolean isWifiSync() {
            return this.wifiSync;
        }

        public void onFinish(List<T> list, List<T> list2) {
            destroy();
        }

        Intent buildBroadcastIntent(String str) {
            return new Intent(str).putExtra(SyncTaskService.EXTRA_TASK_ID, this.taskId);
        }

        public void destroy() {
            Log.d(SyncTaskService.TAG, "Task destroy --- " + this.taskId);
            int i = SyncTaskService.this.runningTask;
            int i2 = this.taskId;
            if ((i & i2) == i2) {
                SyncTaskService.whenDestroy(SyncTaskService.this, ~i2);
                if (SyncTaskService.this.runningTask != 0) {
                    return;
                }
                SyncTaskService.this.stopSelf();
            }
        }
    }

    public void addTask(int id, boolean onlyWifi, SyncTask syncTask) {
        if ((this.runningTask & id) == id) {
            sendBroadcast(new Intent(ACTION_SYNC_ALREADY_SYNC).putExtra(EXTRA_TASK_ID, id));
            return;
        }
        Log.d(TAG, "addTask --- " + id);
        syncTask.setTaskId(id);
        syncTask.setWifiSync(onlyWifi);
        this.syncTasks.add(syncTask);
        runTask();
    }

    private void runTask() {
        while (!this.syncTasks.isEmpty()) {
            SyncTask pop = this.syncTasks.pop();
            if (!pop.isWifiSync() || App.networkState == Enums.NetworkState.wifi) {
                try {
                    pop.run();
                } catch (Exception e) {
                    e.printStackTrace();
                    pop.destroy();
                }
            } else {
                pop.destroy();
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");
        this.syncTasks = new LinkedList<>();
    }
}